package com.paypalpay.controller.common;

import com.paypalpay.config.WxPayConstants;
import com.paypalpay.util.pay.WxJSUtil;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class WeixinSaoController {
    @RequestMapping(value = "/weixinsao", method = RequestMethod.GET)
    @ResponseBody
    @CrossOrigin
    public String scan(Model model, HttpServletRequest request) {
        System.out.println("微信扫描请求的链接是：" + request.getRequestURL() + "?" + request.getQueryString());

        //动态获取调用jssdk扫一扫功能的url
        String jsonString="";
        try {
            String reqUrl=request.getParameter("reqUrl");
            System.out.println("请求过来的url是："+reqUrl);

            String jsUrl=reqUrl.toString();
            System.out.println(jsUrl);
            Map<String, String> ret = WxJSUtil.sign(jsUrl);

            String url1 = ret.get("url");

            String timestamp = ret.get("timestamp");

            String nonceStr = ret.get("nonceStr");

            String signature = ret.get("signature");

            for (Map.Entry entry : ret.entrySet()) {
                System.out.println(entry.getKey() + "=" + entry.getValue());
                model.addAttribute(entry.getKey().toString(), entry.getValue());
            }

            HashMap map = new HashMap();
            map.put("appId", WxPayConstants.APPID);
            map.put("timestamp", timestamp);
            map.put("nonceStr", nonceStr);
            map.put("signature", signature);

            JSONObject jsonObject = JSONObject.fromObject(map);
            System.out.println("输出的结果是：" + jsonObject);
            // 3、将json对象转化为json字符串
            jsonString = jsonObject.toString();
            System.out.println("返回的json是：" + jsonString);
            return jsonString;

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
}

